package com.yuyang.wifi.fragment;

import android.Manifest;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yuyang.wifi.R;
import com.yuyang.wifi.SplashActivity;
import com.yuyang.wifi.activitys.NewMainHomeActivity;
import com.yuyang.wifi.activitys.login.ApkAutoUpgradeActivity;
import com.yuyang.wifi.activitys.login.WeChatLoginActivity;
import com.yuyang.wifi.activitys.mine.AppContants;
import com.yuyang.wifi.activitys.mine.ForceSpeedActivity;
import com.yuyang.wifi.activitys.mine.ForceSpeedGifActivity;
import com.yuyang.wifi.activitys.mine.HintClickActivity;
import com.yuyang.wifi.activitys.mine.NetworkTestSpeedActivity;
import com.yuyang.wifi.activitys.mine.NetworkTestSpeedGifActivity;
import com.yuyang.wifi.activitys.mine.PhoneClearGifActivity;
import com.yuyang.wifi.activitys.mine.PhoneCoolGifActivity;
import com.yuyang.wifi.activitys.mine.SettingActivity;
import com.yuyang.wifi.activitys.mine.WarningActivity;
import com.yuyang.wifi.activitys.web.WebViewSecretActivity;
import com.yuyang.wifi.adapter.NewWifiListAdapter;
import com.yuyang.wifi.base.BaseFragment;
import com.yuyang.wifi.base.BaseResult;
import com.yuyang.wifi.base.Constants;
import com.yuyang.wifi.constant.AppConstant;
import com.yuyang.wifi.dialog.BaseDialogFragment;
import com.yuyang.wifi.dialog.CheckSafeQuestionDialog;
import com.yuyang.wifi.dialog.NetworkContractFailureDialog;
import com.yuyang.wifi.dialog.NetworkSpeedDialog;
import com.yuyang.wifi.dialog.UserProtocolDialog;
import com.yuyang.wifi.dialog.WifiWarnDialog;
import com.yuyang.wifi.model.AdTypeInfoModel;
import com.yuyang.wifi.model.AdTypeInfoResult;
import com.yuyang.wifi.model.CheckUpgradeModel;
import com.yuyang.wifi.model.CheckUpgradeResult;
import com.yuyang.wifi.model.ProtocolModel;
import com.yuyang.wifi.model.ProtocolResult;
import com.yuyang.wifi.model.WifiBean;
import com.yuyang.wifi.utils.CollectionUtils;
import com.yuyang.wifi.utils.DeviceInfoUtils;
import com.yuyang.wifi.utils.DeviceUtil;
import com.yuyang.wifi.utils.MPermissionUtils;
import com.yuyang.wifi.utils.RxUtil;
import com.yuyang.wifi.utils.Skip;
import com.yuyang.wifi.utils.SpUtil;
import com.yuyang.wifi.utils.ToastUtils;
import com.yuyang.wifi.utils.eventbus.BaseEvent;
import com.yuyang.wifi.utils.network.BaseDataSubscriber;
import com.yuyang.wifi.utils.network.HttpErrorHandler;
import com.yuyang.wifi.utils.network.HttpManager;
import com.yuyang.wifi.utils.network.RxDataInstance;
import com.yuyang.wifi.views.LoadCSJiliVideoUtils;
import com.yuyang.wifi.views.LoadCsjMsgUtils;
import com.yuyang.wifi.views.LoadCsjNewInsertFullAdUtils;
import com.yuyang.wifi.views.LoadYLHJiliVideoUtils;
import com.yuyang.wifi.views.NumberRollingView;
import com.yuyang.wifi.views.WifiSupport;
import com.yuyang.wifi.views.recyclerview.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * 连接
 */

public class ContractTabFragment extends BaseFragment {

    @BindView(R.id.tv_network_speed_num)
    TextView tvNetworkSpeedNum;
    @BindView(R.id.tv_network_balance_num)
    TextView tvNetworkBalanceNum;
    @BindView(R.id.tv_network_good_num)
    TextView tvNetworkGoodNum;
    @BindView(R.id.recyclerView_wifi)
    RecyclerView recyclerViewWifi;
    @BindView(R.id.express_container)
    FrameLayout expressContainer;
    @BindView(R.id.express_2_ad_container)
    FrameLayout express2AdContainer;
    @BindView(R.id.tv_contract_wifi_name)
    TextView tvContractWifiName;
    @BindView(R.id.ll_close_wifi_state)
    LinearLayout llCloseWifiState;
    @BindView(R.id.rl_wifi_layout)
    RelativeLayout rlWifiLayout;
    @BindView(R.id.tv_contract_wifi_state)
    TextView tvContractWifiState;

    private static final String TAG = "WifiListActivity";
    //权限请求码
    private static final int PERMISSION_REQUEST_CODE = 0;
    //两个危险权限需要动态申请
    private static final String[] NEEDED_PERMISSIONS = new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    private boolean mHasPermission;
    List<WifiBean> realWifiList = new ArrayList<>();
    private WifiBroadcastReceiver wifiReceiver;
    private NewWifiListAdapter adapter;

    private int connectType = 0;//1：连接成功？ 2 正在连接（如果wifi热点列表发生变需要该字段）
    private WifiManager wifiManager;
    private LoadCsjNewInsertFullAdUtils newInsertAd;
    private LoadYLHJiliVideoUtils loadYLHJiliVideoUtils;
    private boolean isOpenLock = false;
    private String mWifiName;
    private boolean isClickSpeed = false;
    private int mType;

    public static ContractTabFragment newInstance() {
        ContractTabFragment fragment = new ContractTabFragment();
        return fragment;
    }

    @Override
    protected void initActionBar() {

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_home_tab_page;
    }

    @Override
    protected void initBizView() {
        initAdView();
        networkSpeedDialog();
        adapter = new NewWifiListAdapter(getActivity(), realWifiList);
        recyclerViewWifi.setLayoutManager(new LinearLayoutManager(getActivity(),
                LinearLayoutManager.VERTICAL, false));
        recyclerViewWifi.setNestedScrollingEnabled(false);
        recyclerViewWifi.setAdapter(adapter);
        adapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                List<WifiBean> wifiBean = adapter.getData();
                mWifiName = wifiBean.get(position).getWifiName();
                boolean b = checkIsCurrentWifiHasPassword(mWifiName);
                String state = wifiBean.get(position).getState();
                if (state.equals(AppContants.WIFI_STATE_UNCONNECT)) {
                    wifiWarnDialog();
                } else {
                    Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                    startActivity(intent);
                }
            }
        });

        mHasPermission = checkPermission();

        if (!mHasPermission && WifiSupport.isOpenWifi(getActivity())) {  //未获取权限，申请权限
            requestPermission();
        } else if (mHasPermission && WifiSupport.isOpenWifi(getActivity())) {  //已经获取权限
            initRecycler();
        } else {
            Toast.makeText(getActivity(), "WIFI处于关闭状态", Toast.LENGTH_SHORT).show();
        }

    }

    private void initAdView() {

        loadYLHJiliVideoUtils = LoadYLHJiliVideoUtils.getInstance();
        loadYLHJiliVideoUtils.load(getActivity(), "ylh_jl_speed");
//        loadYLHJiliVideoUtils.setLoadFailureListener(new LoadYLHJiliVideoUtils.OnLoadFailureListener() {
//            @Override
//            public void onLoadFailureListener() {
//                newInsertAd.showNewInterAd();
//                newInsertAd.setItemAllClickListener(new LoadCsjNewInsertFullAdUtils.OnItemAllClickListener() {
//                    @Override
//                    public void onItemAllClickListener() {
//                        if (mType == 1) {
//                            isOpenLock = true;
//                        } else {
//                            Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
//                            startActivity(intent);
//                        }
//                    }
//                });
//            }
//        });

        newInsertAd = LoadCsjNewInsertFullAdUtils.getInstance();
        newInsertAd.load(getActivity(), "csj_jl_speed");
//        newInsertAd.setLoadFailureListener(new LoadCsjNewInsertFullAdUtils.OnLoadFailureListener() {
//            @Override
//            public void onLoadFailureListener() {
//                playErrorRepalceAd();
//            }
//        });
    }


    private void playErrorRepalceAd() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                loadYLHJiliVideoUtils.play();
                loadYLHJiliVideoUtils.setAdCloseListener(new LoadYLHJiliVideoUtils.OnAdCloseListener() {
                    @Override
                    public void onAdCloseListenerListener(boolean isPlayComplete) {
                        if (mType == 1) {
                            isOpenLock = true;
                        } else {
                            Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                            startActivity(intent);
                        }
                    }
                });
            }
        }, 1000);
    }

    private void initRecycler() {

        if (WifiSupport.isOpenWifi(getActivity()) && mHasPermission) {
            sortScaResult();
        } else {
            // Toast.makeText(getActivity(), "WIFI处于关闭状态或权限获取失败22222", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        updateNum();
        wifiManager = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.isWifiEnabled() && wifiManager.getConnectionInfo() != null) {
            wifiOpenState();
        } else {
            wifiCloseState();
        }
        //注册广播
        wifiReceiver = new WifiBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);//监听wifi是开关变化的状态
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);//监听wifi连接状态广播,是否连接了一个有效路由
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);//监听wifi列表变化（开启一个热点或者关闭一个热点）
        getActivity().registerReceiver(wifiReceiver, filter);

        if (isOpenLock) {
            networkContractFailureDialog();
            isOpenLock = false;
        } else {
            if (isClickSpeed) {
                if (!isPagerServiceRunning()) {
                    showCheckSafeDialog();
                }
            }
        }
        checkUpgrade();
        String userProtocol = SpUtil.find(AppConstant.KEY_USER_PROTOCOL);
        if (TextUtils.isEmpty(userProtocol)) {
            getProtocolUrl();
        }
    }


    private boolean isPagerServiceRunning() {
        ActivityManager manager = (ActivityManager) getActivity().getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("com.yuyang.wifi.service.LiveWallpaperService".equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }


    private void updateNum() {
        Random random = new Random();
        int num = random.nextInt(30) + 85;
        int nums = random.nextInt(10) + 30;
        int numss = random.nextInt(10) + 30;
        tvNetworkSpeedNum.setText(num + "ms");
        tvNetworkBalanceNum.setText(nums + "%");
        tvNetworkGoodNum.setText(numss + "%");
    }

    private void checkUpgrade() {
        RxDataInstance.getInstance().initMap(getActivity());
        HttpManager.getInstance().getApi().checkUpgrade(RxDataInstance.getInstance().getParamMap())
                .compose(RxUtil.<CheckUpgradeResult>bindLifecycleAndApplySchedulers(this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseDataSubscriber<CheckUpgradeResult>(new HttpErrorHandler() {
                    @Override
                    public void onHttpError(BaseResult result) {
                        ToastUtils.showShortToast(getActivity(), result.getErrorMessage());
                    }

                    @Override
                    public void onHttpException(Throwable e) {
                        // dismissLoadingDialog();
                    }
                }) {
                    @Override
                    public void onDataNext(CheckUpgradeResult result) {
                        int resultCode = result.getResultCode();
                        if (0 == resultCode) {
                            CheckUpgradeModel data = result.getData();
                            if (null != data) {
                                int newCode = data.getVersioncode();
                                int localVersionCode = DeviceInfoUtils.getLocalVersionCode(getActivity());
                                if (newCode > Integer.valueOf(localVersionCode)) {
                                    Intent intent = new Intent(getActivity(), ApkAutoUpgradeActivity.class);
                                    intent.putExtra("data", data);
                                    startActivity(intent);
                                } else {
                                    // ToastUtils.showShortToast(getActivity(), "当前已经是最新版本");
                                }
                            }
                        } else {
                            ToastUtils.showShortToast(getActivity(), result.getErrorMessage());
                        }
                    }
                });
    }

    private void getProtocolUrl() {
        RxDataInstance.getInstance().initMap(getActivity());
        HttpManager.getInstance().getApi().getProtocolUrl(RxDataInstance.getInstance().getParamMap())
                .compose(RxUtil.<ProtocolResult>bindLifecycleAndApplySchedulers(this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseDataSubscriber<ProtocolResult>(new HttpErrorHandler() {
                    @Override
                    public void onHttpError(BaseResult result) {
                        ToastUtils.showShortToast(getActivity(), result.getErrorMessage());
                    }

                    @Override
                    public void onHttpException(Throwable e) {
                        // dismissLoadingDialog();
                    }
                }) {
                    @Override
                    public void onDataNext(ProtocolResult result) {
                        int resultCode = result.getResultCode();
                        if (0 == resultCode) {
                            ProtocolModel data = result.getData();
                            if (null != data) {
                                String privacyagreement = data.getPrivacyagreement();
                                String useragreement = data.getUseragreement();
                                SpUtil.saveOrUpdate(AppConstant.KEY_USER_PROTOCOL, useragreement);
                                SpUtil.saveOrUpdate(AppConstant.KEY_PRIVACY_PROTOCOL, privacyagreement);
                            }
                        } else {
                            ToastUtils.showShortToast(getActivity(), result.getErrorMessage());
                        }
                    }
                });
    }


    @Override
    public void onPause() {
        super.onPause();
        getActivity().unregisterReceiver(wifiReceiver);
    }

    //监听wifi状态
    public class WifiBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                switch (state) {
                    /**
                     * WIFI_STATE_DISABLED    WLAN已经关闭
                     * WIFI_STATE_DISABLING   WLAN正在关闭
                     * WIFI_STATE_ENABLED     WLAN已经打开
                     * WIFI_STATE_ENABLING    WLAN正在打开
                     * WIFI_STATE_UNKNOWN     未知
                     */
                    case WifiManager.WIFI_STATE_DISABLED: {
                        Log.d(TAG, "已经关闭");
                        wifiCloseState();
                        // Toast.makeText(getActivity(), "WIFI处于关闭状态", Toast.LENGTH_SHORT).show();
                        break;
                    }
                    case WifiManager.WIFI_STATE_DISABLING: {
                        Log.d(TAG, "正在关闭");
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLED: {
                        Log.d(TAG, "已经打开");
                        wifiOpenState();
                        sortScaResult();
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLING: {
                        Log.d(TAG, "正在打开");
                        break;
                    }
                    case WifiManager.WIFI_STATE_UNKNOWN: {
                        Log.d(TAG, "未知状态");
                        break;
                    }
                }
            } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                Log.d(TAG, "--NetworkInfo--" + info.toString());
                if (NetworkInfo.State.DISCONNECTED == info.getState()) {//wifi没连接上
                    Log.d(TAG, "wifi没连接上");
                    tvContractWifiName.setText("未连接");
                    for (int i = 0; i < realWifiList.size(); i++) {//没连接上将 所有的连接状态都置为“未连接”
                        realWifiList.get(i).setState(AppContants.WIFI_STATE_UNCONNECT);
                    }
                    adapter.notifyDataSetChanged();
                } else if (NetworkInfo.State.CONNECTED == info.getState()) {//wifi连接上了
                    Log.d(TAG, "wifi连接上了");
                    WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());
                    if (wifiManager.getConnectionInfo() != null && wifiManager.getConnectionInfo().getIpAddress() != 0) {
                        tvContractWifiName.setText(wifiManager.getConnectionInfo().getSSID().replace("\"", ""));
                        wifiOpenState();
                    }
                    //连接成功 跳转界面 传递ip地址
                    //Toast.makeText(getActivity(), "wifi连接上了", Toast.LENGTH_SHORT).show();
                    connectType = 1;
                    wifiListSet(connectedWifiInfo.getSSID(), connectType);
                } else if (NetworkInfo.State.CONNECTING == info.getState()) {//正在连接
                    Log.d(TAG, "wifi正在连接");
                    //Toast.makeText(getActivity(), "wifi正在连接", Toast.LENGTH_SHORT).show();
                    WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());
                    connectType = 2;
                    wifiListSet(connectedWifiInfo.getSSID(), connectType);
                }
            } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {
                Log.d(TAG, "网络列表变化了");
                wifiListChange();
            }
        }
    }

    /**
     * //网络状态发生改变 调用此方法！
     */
    public void wifiListChange() {
        sortScaResult();
        WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());
        if (connectedWifiInfo != null) {
            wifiListSet(connectedWifiInfo.getSSID(), connectType);
        }
    }

    /**
     * 将"已连接"或者"正在连接"的wifi热点放置在第一个位置
     *
     * @param wifiName
     * @param type
     */
    public void wifiListSet(String wifiName, int type) {
        int index = -1;
        WifiBean wifiInfo = new WifiBean();
        if (CollectionUtils.isNullOrEmpty(realWifiList)) {
            return;
        }
        for (int i = 0; i < realWifiList.size(); i++) {
            realWifiList.get(i).setState(AppContants.WIFI_STATE_UNCONNECT);
        }
        Collections.sort(realWifiList);//根据信号强度排序
        for (int i = 0; i < realWifiList.size(); i++) {
            WifiBean wifiBean = realWifiList.get(i);
            if (index == -1 && ("\"" + wifiBean.getWifiName() + "\"").equals(wifiName)) {
                index = i;
                wifiInfo.setLevel(wifiBean.getLevel());
                wifiInfo.setWifiName(wifiBean.getWifiName());
                wifiInfo.setCapabilities(wifiBean.getCapabilities());
                if (type == 1) {
                    wifiInfo.setState(AppContants.WIFI_STATE_CONNECT);
                } else {
                    wifiInfo.setState(AppContants.WIFI_STATE_ON_CONNECTING);
                }
            }
        }
        if (index != -1) {
            realWifiList.remove(index);
            realWifiList.add(0, wifiInfo);
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 检查是否已经授予权限
     *
     * @return
     */
    private boolean checkPermission() {
        for (String permission : NEEDED_PERMISSIONS) {
            if (ActivityCompat.checkSelfPermission(getActivity(), permission)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 申请权限
     */
    private void requestPermission() {
        ActivityCompat.requestPermissions(getActivity(),
                NEEDED_PERMISSIONS, PERMISSION_REQUEST_CODE);
    }

    /**
     * 获取wifi列表然后将bean转成自己定义的WifiBean
     */
    public void sortScaResult() {
        List<ScanResult> scanResults = WifiSupport.noSameName(WifiSupport.getWifiScanResult(getActivity()));
        realWifiList.clear();
        if (!CollectionUtils.isNullOrEmpty(scanResults)) {
            for (int i = 0; i < scanResults.size(); i++) {
                WifiBean wifiBean = new WifiBean();
                //wifiBean.setJM(checkIsCurrentWifiHasPassword(scanResults.get(i).SSID));
                wifiBean.setWifiName(scanResults.get(i).SSID);
                wifiBean.setState(AppContants.WIFI_STATE_UNCONNECT);   //只要获取都假设设置成未连接，真正的状态都通过广播来确定
                wifiBean.setCapabilities(scanResults.get(i).capabilities);
                wifiBean.setLevel(WifiSupport.getLevel(scanResults.get(i).level) + "");
                realWifiList.add(wifiBean);

                //排序
                Collections.sort(realWifiList);
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasAllPermission = true;
        if (requestCode == PERMISSION_REQUEST_CODE) {
            for (int i : grantResults) {
                if (i != PackageManager.PERMISSION_GRANTED) {
                    hasAllPermission = false;   //判断用户是否同意获取权限
                    break;
                }
            }

            //如果同意权限
            if (hasAllPermission) {
                mHasPermission = true;
                if (WifiSupport.isOpenWifi(getActivity()) && mHasPermission) {  //如果wifi开关是开 并且 已经获取权限
                    initRecycler();
                } else {
                    //Toast.makeText(getActivity(), "WIFI处于关闭状态或权限获取失败1111", Toast.LENGTH_SHORT).show();
                }

            } else {  //用户不同意权限
                mHasPermission = false;
                // Toast.makeText(getActivity(), "获取权限失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void wifiCloseState() {
        llCloseWifiState.setVisibility(View.VISIBLE);
        rlWifiLayout.setVisibility(View.GONE);
        tvContractWifiState.setText("未打开");
    }

    private void wifiOpenState() {
        llCloseWifiState.setVisibility(View.GONE);
        rlWifiLayout.setVisibility(View.VISIBLE);
        tvContractWifiState.setText("已连接");
    }


    @OnClick({R.id.rl_top_setting, R.id.rl_fast_speed, R.id.rl_phone_test_network_speed, R.id.rl_lunch_protect,
            R.id.rl_phone_clear, R.id.rl_phone_cool, R.id.tv_open_wifi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_top_setting:
                Skip.toActivity(getActivity(), SettingActivity.class);
                break;
            case R.id.rl_lunch_protect:
                Skip.toActivity(getActivity(), WarningActivity.class);
                break;
            case R.id.rl_fast_speed:
                Skip.toActivity(getActivity(), ForceSpeedGifActivity.class);
                break;
            case R.id.rl_phone_test_network_speed:
                Skip.toActivity(getActivity(), NetworkTestSpeedGifActivity.class);
                break;
            case R.id.rl_phone_clear:
                Skip.toActivity(getActivity(), PhoneClearGifActivity.class);
                break;
            case R.id.rl_phone_cool:
                Skip.toActivity(getActivity(), PhoneCoolGifActivity.class);
                break;
            case R.id.tv_open_wifi:
                if (!wifiManager.isWifiEnabled()) {
                    wifiManager.setWifiEnabled(true);
                }
                break;
        }
    }

    public void showCheckSafeDialog() {
        CheckSafeQuestionDialog checkSafeQuestionDialog = CheckSafeQuestionDialog.newInstance();
        checkSafeQuestionDialog.showDialog(getActivity().getFragmentManager());
        checkSafeQuestionDialog.setOnDialogListener(new BaseDialogFragment.DialogListener() {
            @Override
            public void onConfirm() {
                Skip.toActivity(getActivity(), WarningActivity.class);
            }

            @Override
            public void onInputConfirm(String... values) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onSendCode() {

            }
        });
    }

    public void wifiWarnDialog() {
        WifiWarnDialog wifiWarnDialog = WifiWarnDialog.newInstance();
        wifiWarnDialog.showDialog(getActivity().getFragmentManager());
        wifiWarnDialog.setOnDialogListener(new BaseDialogFragment.DialogListener() {
            @Override
            public void onConfirm() {
                //免费解锁
                mType = 1;
                getAdTypeInfo(1);
            }

            @Override
            public void onInputConfirm(String... values) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onSendCode() {
                //直接进入
                mType = 2;
                getAdTypeInfo(2);
            }
        });
    }

    private void getAdTypeInfo(int mType) {
        RxDataInstance.getInstance().initMap(getActivity())
                .put("entryNumber", "2");
        HttpManager.getInstance().getApi().getAdTypeInfo(RxDataInstance.getInstance().getParamMap())
                .compose(RxUtil.<AdTypeInfoResult>bindLifecycleAndApplySchedulers(this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseDataSubscriber<AdTypeInfoResult>(new HttpErrorHandler() {
                    @Override
                    public void onHttpError(BaseResult result) {
                        ToastUtils.showShortToast(getActivity(), result.getErrorMessage());
                    }

                    @Override
                    public void onHttpException(Throwable e) {
                        // dismissLoadingDialog();
                    }
                }) {
                    @Override
                    public void onDataNext(AdTypeInfoResult result) {
                        int resultCode = result.getResultCode();
                        if (0 == resultCode) {
                            AdTypeInfoModel data = result.getData();
                            if (null != data) {
                                int type = data.getType();
                                if (type == 1) {
                                    newInsertAd.showNewInterAd();
                                    newInsertAd.setItemAllClickListener(new LoadCsjNewInsertFullAdUtils.OnItemAllClickListener() {
                                        @Override
                                        public void onItemAllClickListener() {
                                            if (mType == 1) {
                                                isOpenLock = true;
                                            } else {
                                                Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                                                startActivity(intent);
                                            }
                                        }
                                    });
                                } else if (type == 2) {
                                    loadYLHJiliVideoUtils.play();
                                    loadYLHJiliVideoUtils.setAdCloseListener(new LoadYLHJiliVideoUtils.OnAdCloseListener() {
                                        @Override
                                        public void onAdCloseListenerListener(boolean isPlayComplete) {
                                            if (mType == 1) {
                                                isOpenLock = true;
                                            } else {
                                                Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                                                startActivity(intent);
                                            }
                                        }
                                    });
                                }
                            }
                        } else {
                            ToastUtils.showShortToast(getActivity(), result.getErrorMessage());
                        }
                    }
                });
    }

    public void networkSpeedDialog() {
        NetworkSpeedDialog networkSpeedDialog = NetworkSpeedDialog.newInstance();
        networkSpeedDialog.showDialog(getActivity().getFragmentManager());
        networkSpeedDialog.setOnDialogListener(new BaseDialogFragment.DialogListener() {
            @Override
            public void onConfirm() {
                //立即加速
                Skip.toActivity(getActivity(), NetworkTestSpeedGifActivity.class);
                isClickSpeed = true;
            }

            @Override
            public void onInputConfirm(String... values) {

            }

            @Override
            public void onCancel() {
                isClickSpeed = true;
            }

            @Override
            public void onSendCode() {

            }
        });
    }


    public void networkContractFailureDialog() {
        NetworkContractFailureDialog networkContractFailureDialog = NetworkContractFailureDialog.newInstance();
        networkContractFailureDialog.setData(getActivity(), mWifiName);
        networkContractFailureDialog.showDialog(getActivity().getFragmentManager());
        networkContractFailureDialog.setOnDialogListener(new BaseDialogFragment.DialogListener() {
            @Override
            public void onConfirm() {
                mType = 1;
                getAdTypeInfo(1);
            }

            @Override
            public void onInputConfirm(String... values) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onSendCode() {

            }
        });
    }

    /**
     * 利用WifiConfiguration.KeyMgmt的管理机制，来判断当前wifi是否需要连接密码
     *
     * @return true：需要密码连接，false：不需要密码连接
     */
    public boolean checkIsCurrentWifiHasPassword(String currentWifiSSID) {

        if (null != wifiManager) {
            // 得到当前连接的wifi热点的信息
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            // 得到当前WifiConfiguration列表，此列表包含所有已经连过的wifi的热点信息，未连过的热点不包含在此表中
            List<WifiConfiguration> wifiConfiguration = wifiManager.getConfiguredNetworks();
            String currentSSID = wifiInfo.getSSID();
            if (currentSSID != null && currentSSID.length() > 2) {
                if (currentSSID.startsWith("\"") && currentSSID.endsWith("\"")) {
                    currentSSID = currentSSID.substring(1, currentSSID.length() - 1);
                }

                if (wifiConfiguration != null && wifiConfiguration.size() > 0) {
                    for (WifiConfiguration configuration : wifiConfiguration) {
                        if (configuration != null && configuration.status == WifiConfiguration.Status.CURRENT) {
                            String ssid = null;
                            if (!TextUtils.isEmpty(configuration.SSID)) {
                                ssid = configuration.SSID;
                                if (configuration.SSID.startsWith("\"") && configuration.SSID.endsWith("\"")) {
                                    ssid = configuration.SSID.substring(1, configuration.SSID.length() - 1);
                                }
                            }
                            if (TextUtils.isEmpty(currentSSID) || currentSSID.equalsIgnoreCase(ssid)) {
                                //KeyMgmt.NONE表示无需密码
                                return (!configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE));
                            }
                        }
                    }
                }
            }
        }
        //默认为需要连接密码
        return true;
    }
}

